package com.hyperfix.simulator.service.impl;

import com.hyperfix.common.exception.CustomException;
import com.hyperfix.models.simulator.pojos.ScheduleSetting;
import com.hyperfix.simulator.mapper.SysJobMapper;
import com.hyperfix.simulator.senor.CombinationSenor;
import com.hyperfix.simulator.timer.SysJob;
import com.hyperfix.simulator.timer.CronTaskRegistrar;
import com.hyperfix.models.common.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author JiangChunYu
 * 2024/3/14
 */
@Transactional
@Service
public class SysJobServiceImpl implements SysJobService {
    @Resource
    private SysJobMapper sysJobMapper;
    @Resource
    CronTaskRegistrar cronTaskRegistrar;

    @Override
    public R<String> changeStatus(Integer pipelineId, Integer stop) {
        int updateRows = sysJobMapper.updateStatusByPipelineId(pipelineId, stop);
        if (updateRows == 0) {
            return R.error("管线启用/停用失败");
        }
        ScheduleSetting ss = sysJobMapper.selectOneByPipelineId(pipelineId);
        if (Integer.valueOf(1).equals(stop)) {
            updateTask(ss);
        } else {
            cronTaskRegistrar.removeCronTask(ss.getJobId());
        }
        return R.success("管线启用/停用成功");
    }

    @Override
    public R<String> changeCycle(Integer pipelineId, Long period) {
        String newCron = new StringBuilder("*/1 * * * * ?")
                .replace(2, 3, period.toString())
                .toString();
        int updateRows = sysJobMapper.updateCycleByPipelineId(pipelineId, newCron);
        if (updateRows == 0) {
            throw new CustomException("设置采集周期失败");
        }
        ScheduleSetting ss = sysJobMapper.selectOneByPipelineId(pipelineId);
        updateTask(ss);
        return R.success("采集周期设置成功");
    }

    private void updateTask(ScheduleSetting ss) {
        CombinationSenor senor = new CombinationSenor(ss.getStation(), ss.getPipeline());
        SysJob sysJob = new SysJob(ss.getJobId(), senor);
        cronTaskRegistrar.addCronTask(sysJob, ss.getCronExpression());
    }
}
